# vim:fileencoding=utf-8
#    Plugin climobike_arduino para matebot: Lê dados seriais de um ClimoBike 0.2
#    Copyleft (C) 2016-2018 Desobediente Civil, Matehackers

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import serial, datetime

def raw(info_dict, bot_dict, addr_dict, command_list):
  try:
    ## TODO tentar descobrir em que terminal o dispositivo está montado, permitir a escolha por parâmetro enviado pelo telegram, etc.
    limite = 3
    if len(command_list) > 0:
      if command_list[0].isdigit():
        limite = int(command_list[0])
    tempo_limite = (datetime.datetime.now() + datetime.timedelta(seconds=limite))
    arduino = '/dev/ttyACM0'
    baud = 9600
    sensor = serial.Serial(arduino, baud)
    response = list()
    response.append(str(sensor.readline()))
    while (datetime.datetime.now() < tempo_limite):
      response.append(str(sensor.readline()))
    return {
      'status': True,
      'type': 'grupo',
      'multi': True,
      'response': '\n'.join(response),
      'debug': u'ClimoBike raw bem sucedido',
    }
  except Exception as e:
    return {
      'status': False,
      'type': 'erro',
      'response':  u'Nao deu certo.',
      'debug': u'ClimoBike raw erro\nExceção: %s' % (e),
    }

